package com.cjst.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cjst.pojo.base.ShortMessage;
import com.cjst.service.base.ShortMessageService;
import com.cjst.util.common.DateUtil;

@Component
public class SendSmsUtil {
	@Autowired
	private ShortMessageService shortMessageService;
	ExecutorService executor = Executors.newCachedThreadPool();
	private static ApplicationContext applicationContext;
    public static void setApplicationContext(ConfigurableApplicationContext context) {
    	SendSmsUtil.applicationContext = context;
    }
    public String ss(String templateParamJsonString){
    	 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunSmsUtil.accessKeyId, AliyunSmsUtil.accessSecret);
         IAcsClient client = new DefaultAcsClient(profile);

         CommonRequest request = new CommonRequest();
         request.setMethod(MethodType.POST);
         request.setDomain("dysmsapi.aliyuncs.com");
         request.setVersion("2017-05-25");
         request.setAction("SendSms");
         request.putQueryParameter("RegionId", "cn-hangzhou");
         request.putQueryParameter("PhoneNumbers", "13058127893");
         request.putQueryParameter("SignName", "城基生态");
         request.putQueryParameter("TemplateCode", "SMS_166455001");
         //request.putQueryParameter("TemplateParam", "{\"code\":\"1213\"}");
         request.putQueryParameter("TemplateParam", templateParamJsonString);
         try {
             CommonResponse response = client.getCommonResponse(request);
             System.out.println(response.getData());
             return response.getData();
         } catch (ServerException e) {
             e.printStackTrace();
         } catch (ClientException e) {
             e.printStackTrace();
         }
         return null;
    }
    /**
     * 发送短信基础
     * @param phoneNumbers
     * @param templateCode
     * @param templateParamJsonString
     * @param sendAction
     * @param signName
     * @return
     */
    public String sendBaseSms(String phoneNumbers,String templateCode,String templateParamJsonString,String sendAction,String signName){
    	DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunSmsUtil.accessKeyId, AliyunSmsUtil.accessSecret);
	    IAcsClient client = new DefaultAcsClient(profile);
	    CommonRequest request = new CommonRequest();
	    request.setMethod(MethodType.POST);
	    request.setDomain(AliyunSmsUtil.domain);
	    request.setVersion(AliyunSmsUtil.version);
	    request.setAction(sendAction);
	    request.putQueryParameter("RegionId",AliyunSmsUtil.regionId);
	    request.putQueryParameter("PhoneNumbers", phoneNumbers);
	    request.putQueryParameter("SignName", signName);
	    request.putQueryParameter("TemplateCode", templateCode);						//SMS_166455001
	    if(templateParamJsonString!=null && templateParamJsonString.length()!=0){
	    	request.putQueryParameter("TemplateParam", templateParamJsonString);
	    }
	    try {
	    	CommonResponse response = client.getCommonResponse(request);
	    	return response.getData();
	    } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
	    return null;
    }
    /**
     * 发送短信封装，常规调用此方法
     * @param phoneNumbers
     * @param templateCode
     * @param templateParamMap
     * @param userId
     * @param sendAction
     * @param signName
     * @param smsBusiness
     * @return
     */
	public String sendSms(String phoneNumbers,String templateCode,Map<String, Object> templateParamMap,String userId,String sendAction,String signName,String smsBusiness){
		if(sendAction==null || sendAction.length()==0){
			sendAction="SendSms";
		}
		if(signName==null || signName.length()==0){
			signName="植城智慧";
		}
		if(phoneNumbers==null || phoneNumbers.length()==0){
			return null;
		}
		if(templateCode==null || templateCode.length()==0){
			return null;
		}
		String jsonString="";
	    if(templateParamMap!=null){
	    	JSONObject json = new JSONObject(templateParamMap);
	    	jsonString = JSONObject.toJSONString(json);
	    }
	    
        String data=sendBaseSms(phoneNumbers, templateCode, jsonString, sendAction, signName);
        ShortMessage sms=new ShortMessage();
        JSONObject rowData = JSONObject.parseObject(data);
        String isScc=(String) rowData.get("Message");
        if(isScc.equals("OK")){
        	sms.setIsSuccess(0);
        }else{
        	sms.setIsSuccess(1);
        }
        if(templateParamMap!=null){
        	sms.setSmsTemplateCode(templateParamMap.toString());
        }
        sms.setSmsTemplateCode(templateCode);
        sms.setSmsBusiness(smsBusiness);
        sms.setUserId(userId);
        sms.setSmsPhone(phoneNumbers);
        sms.setCreateTime(DateUtil.dateFormatToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        shortMessageService.addLocalByid(sms);
		return isScc;
	}
	public String sendSmsEx(String phoneNumbers,String templateCode,Map<String, Object> templateParamMap,String userId,String sendAction,String signName,String smsBusiness){
		executor.submit(() -> sendSms(phoneNumbers, templateCode,templateParamMap,userId,sendAction,signName,smsBusiness));
		return "OK";
	}
	public void destroy(){
		try{
			executor.shutdown();
		}
		catch(Exception e){}
	}
	/**
	 * 模板查询
	 * @param templateCode
	 */
	public String querySmsTemplate(String templateCode){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunSmsUtil.accessKeyId, AliyunSmsUtil.accessSecret);
	    IAcsClient client = new DefaultAcsClient(profile);
	    CommonRequest request = new CommonRequest();
	    request.setMethod(MethodType.POST);
	    request.setDomain(AliyunSmsUtil.domain);
	    request.setVersion(AliyunSmsUtil.version);
	    request.setAction("QuerySmsTemplate");
	    request.putQueryParameter("TemplateCode", templateCode);
	    try {
			CommonResponse response = client.getCommonResponse(request);
			return response.getData();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return null;
	}
	/*public static void main(String[] args) {
		Map<String, Object> templateParamMap =new HashMap<String, Object>();
		//SendSmsUtil sms=new SendSmsUtil();
		//sms.querySmsTemplate("SMS_166455001");
		templateParamMap.put("code", "1213");
		//templateParamMap.put("content", "不明火源");
		String jsonString="";
		JSONObject json = new JSONObject(templateParamMap);
    	jsonString = JSONObject.toJSONString(json);
		SendSmsUtil s=new SendSmsUtil();
		//System.out.println(s.ss());
    	//System.out.println(s.sendBaseSms("13058127893", "SMS_177360063", jsonString, "SendSms", "植城智慧"));
		System.out.println(s.sendBaseSms("13058127893", "SMS_166455001", jsonString, "SendSms", "城基生态"));
	}*/
}












